package test.email;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class EmailManager {
	public void sendEmail(EmailForm emailForm) throws UnsupportedEncodingException, MessagingException{

		// 프로퍼티 값 인스턴스 생성과 기본세션(SMTP 서버 호스트 지정)
	    Properties props = new Properties();
	    // G-Mail SMTP 사용시
	    props.put("mail.smtp.starttls.enable","true");
	    props.put("mail.transport.protocol","smtp");
	    props.put("mail.smtp.host", emailForm.getHost());
//	    props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocktFactory"); //암호화된 메일 보낼때 사용(지원하는곳만 사용가능)
	    props.put("mail.smtp.port","25");
	    props.put("mail.smtp.user", emailForm.getFrom());
	    props.put("mail.smtp.auth","true");

	    MyAuthenticator auth = new MyAuthenticator("mansoo1500@gmail.com","kane5263");
	    Session mailSession = Session.getDefaultInstance(props, auth);

	    Message msg = new MimeMessage(mailSession);
	    msg.setFrom(new InternetAddress(emailForm.getFrom(), MimeUtility.encodeText(emailForm.getFrom(),"UTF-8","B"))); //보내는 사람 설정
	    InternetAddress[] address = {new InternetAddress(emailForm.getTo())};

	    msg.setRecipients(Message.RecipientType.TO, address); //받는 사람설정

	    msg.setSubject(emailForm.getSubject()); //제목설정
	    msg.setSentDate(new java.util.Date()); //보내는 날짜 설정
	    msg.setContent(emailForm.getContent(),"text/html; charset=EUC-KR"); //내용 설정(MIME 지정-HTML 형식)
	    
	    Transport.send(msg); //메일 보내기

	    System.out.println("메일 발송을 완료하였습니다.");

	}
}
